<template>
  <el-dialog
      class="dialog"
      title="差额征税计算"
      :visible="showDialog"
      width="70%"
      :before-close="closeSearch"
      :append-to-body="true"
  >
    <div class='form-con'>
      <el-form
          :model="searchFormData"
          :rules="collectDataRules"
          label-width="120px"
          size="mini"
          :inline-message="true"
          ref="searchForm"
      >
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <el-card class="box-body">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="含税金额:" prop="taxAmount">
                    <el-input v-model="searchFormData.taxAmount" type="number" placeholder="请输入"
                              @blur="handTaxAmount"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="扣除额:">
                    <el-input v-model="searchFormData.minusAmount" type="number" disabled></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </div>
          <el-card class="box-body" v-for="(item,index) in searchFormData.cekcList" :key="item.localId || index">
            <div slot="header" class="clearfix">
              <span>第{{ index + 1 }}条</span>
              <el-button v-if="index+1 === searchFormData.cekcList.length"
                         style="float: right; padding: 3px 5px" type="text" @click="addRow">增加一行
              </el-button>
              <el-button style="float: right; padding: 3px 0" type="text" @click="removeRow(index)">删除</el-button>
            </div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="凭证类型:" :prop="'cekcList.'+index+'.pzlx'"
                              :rules="{required: true,message: '请选择凭证类型',trigger: 'change'}">
                  <el-select v-model="item.pzlx" clearable style="width: 100%"
                             placeholder="请选择" @change="handChangePzlx(index,item)">
                    <el-option label="数电票" value="01"></el-option>
                    <el-option label="增值税专用发票" value="02"></el-option>
                    <el-option label="增值税普通发票" value="03"></el-option>
                    <el-option label="营业税发票" value="04"></el-option>
                    <el-option label="财政票据" value="05"></el-option>
                    <el-option label="法院裁决书" value="06"></el-option>
                    <el-option label="契税完税凭证" value="07"></el-option>
                    <el-option label="其他发票类" value="08"></el-option>
                    <el-option label="其他扣除凭证" value="09"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发票代码:" :prop="'cekcList.'+index+'.fpdm'"
                              :rules="{ required: item.pzlx==='02' || item.pzlx === '03'|| item.pzlx === '04',
                                message: '请输入发票代码',
                                trigger: 'blur' }">
                  <el-input v-model="item.fpdm" :placeholder="(item.pzlx==='01' || item.pzlx === '05'|| item.pzlx === '06'|| item.pzlx === '07'|| item.pzlx === '09')?' ':'请输入'" :maxlength="12" :disabled="(item.pzlx==='01' || item.pzlx === '05'|| item.pzlx === '06'|| item.pzlx === '07'|| item.pzlx === '09')">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="发票号码:" :prop="'cekcList.'+index+'.fphm'"
                              :rules="{ required: item.pzlx==='01' || item.pzlx==='02' || item.pzlx === '03'|| item.pzlx === '04' ,
                                message: '请输入发票号码',
                                trigger: 'blur'}">
                  <el-input v-model="item.fphm" placeholder="请输入" type="number"
                            oninput="if(value.length > 20) value=value.slice(0, 20)"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="凭证号码:">
                  <el-input v-model="item.cepzhm" placeholder="请输入" type="number"
                            oninput="if(value.length > 20) value=value.slice(0, 20)"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开具日期:" :prop="'cekcList.'+index+'.kjrq'"
                              :rules="{ required: item.pzlx==='01' || item.pzlx === '02' || item.pzlx === '03'|| item.pzlx === '04',
                                 message: '请选择日期',
                                 trigger: 'change' }">
                  <el-date-picker style="width: 100%" v-model="item.kjrq" type="date" value-format="yyyy-MM-dd"
                                  placeholder="选择日期" :picker-options="pickerOptions"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注:" :prop="'cekcList.'+index+'.bz'"
                              :rules="{ required: item.pzlx==='08' || item.pzlx === '09', message: '请输入备注', trigger: 'blur' }">
                  <el-input v-model="item.bz" placeholder="请输入" :maxlength="100"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="凭证合计金额:" :prop="'cekcList.'+index+'.pzhjje'"
                              :rules="{ required: true, message: '请输入凭证合计金额', trigger: 'blur' }">
                  <el-input v-model="item.pzhjje" type="number" placeholder="请输入"
                    @blur="jeBlur(item,'pzhjje')"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="本次扣除金额:" :prop="'cekcList.'+index+'.bckcje'"
                              :rules="{ required: true, message: '请输入本次扣除金额', trigger: 'blur' }">
                  <el-input v-model="item.bckcje" type="number" placeholder="请输入"
                            @blur="jeBlur(item,'bckcje')"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-card>
      </el-form>


      <!--        <vxe-form  :data="searchFormData" ref='searchForm' @submit="submitSearch" :rules="collectDataRules" size="mini" title-align="right" title-width="300" style="width: 100%">-->
      <!--              <vxe-form-item title="含税金额：" field="taxAmount" :item-render="{}" >-->
      <!--                <template v-slot>-->
      <!--                  <el-input  v-model="searchFormData.taxAmount" type="number" step="0.01" placeholder="请输入" class="my-search" ></el-input>-->
      <!--                </template>-->
      <!--              </vxe-form-item>-->
      <!--              <vxe-form-item title="扣除额：" field="minusAmount" :item-render="{}">-->
      <!--                <template v-slot>-->
      <!--                  <el-input  v-model="searchFormData.minusAmount" type="number" step="0.01" placeholder="请输入" class="my-search" @input="kceChange(searchFormData)"></el-input>-->
      <!--                </template>-->
      <!--              </vxe-form-item>-->
      <!--        </vxe-form>-->
      <div class="button">
        <vxe-button @click="closeSearch" status="info">取消</vxe-button>
        <vxe-button @click="submitSearch" status="primary">保存</vxe-button>
      </div>
    </div>

  </el-dialog>
</template>
<script>
import {mixin} from '@/utils/mixin.js'
import {valitedLimitNumber} from '@/utils/validate.js';
import { cloneDeep } from 'lodash'

export default {
  name: 'searchFormComp',
  mixins: [mixin],
  data() {
    return {
      searchFormData: {
        taxAmount: 0, //搜索输入框内容
        minusAmount: 0,
        cekcList: [
          {
            xh: '', // 序号
            pzlx: '',
            fpdm: '',
            fphm: '',
            cepzhm: '',
            kjrq: '',
            pzhjje: '',
            bckcje: '',
            bz: '',
          }
        ],
      },
      collectDataRules: {
        taxAmount: [
          {required: true, message: '请输入含税金额', trigger: 'blur'}
        ],
        minusAmount: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        pzlx: [
          {required: true, message: '请选择', trigger: 'change'}
        ],
        pzhjje: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        bckcje: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
      },
      showDialog: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    }
  },
  components: {},
  // mixins: [mixin],
  created() {
  },
  mounted() {

  },
  methods: {
    kceChange(row) {
      row.minusAmount = valitedLimitNumber(row.minusAmount, {leftLength: 16, rightLength: 2,})
    },
    reset() {
      this.searchFormData = {
        taxAmount: 0,
        minusAmount: 0,
        cekcList: [
          {
            pzlx: '',
            fpdm: '',
            fphm: '',
            cepzhm: '',
            kjrq: '',
            pzhjje: '',
            bckcje: '',
            bz: '',
          }
        ],
      }
    },
    async submitSearch() {
      await this.$refs.searchForm.validate((valid) => {
        if (valid) {
          // 定义不同凭证类型对应的必填关键字列表及其名称
          const requiredKeywordsMap = {
            '08': { keywords: ['机打发票', '定期定额'], name: '其他发票' },
            '09': { keywords: ['劳务派遣员工工资', '福利', '社会保险', '住房公积金'], name: '其他扣除凭证' }
          };

          // 遍历 cekcList，检查每个项目的备注是否包含对应凭证类型的必填关键字中的任意一个
          for (const item of this.searchFormData.cekcList) {
            const pzlx = item.pzlx;
            const entry = requiredKeywordsMap[pzlx];

            if (!entry) {
              continue; // 跳过当前项目，因无此凭证类型的必填关键字定义
            }

            const { keywords, name } = entry;

            if (!keywords || !item.bz) {
              continue; // 备注为空或无必填关键字定义，跳过当前循环
            }

            const missingKeywords = keywords.filter(keyword => !item.bz?.includes(keyword));
            if (missingKeywords.length === keywords.length) {
              this.$message.warning(`凭证类型为“${name}”的备注中未包含以下任一必填关键字：“${keywords.join('、')}”`);
              return;
            }
          }


          let temp = '0';
          for (const i in this.searchFormData.cekcList) {
            const item = this.searchFormData.cekcList[i];
            if (item.pzhjje) {
              let r1 = valitedLimitNumber(this.bigNumFixed(item.pzhjje), {leftLength: 16, rightLength: 2,})
              let r2 = valitedLimitNumber(this.bigNumFixed(item.bckcje), {leftLength: 16, rightLength: 2,})
              temp = this.bigNumAdd(r1, temp)
              // 本次扣除金额不能大于凭证合计金额
              if (this.bigNumcomparedTo(r2, r1)) {
                  this.$message.warning('第'+ (+i+1) +'条数据:本次扣除金额不能大于凭证合计金额')
                return
              }
            }
          }

          temp = this.bigNumFixed(temp)
 
          if (this.bigNumcomparedTo(this.searchFormData.taxAmount, temp)) {
            this.$message.warning('含税金额不能大于凭证合计金额')
            return
          }
          let taxAmount = this.searchFormData.taxAmount
          let minusAmount = this.searchFormData.minusAmount
          let slv = this.slv;
          let twoSlv = this.bigNumAdd(slv, 1);
          let res1 = this.bigNumLessen(taxAmount, minusAmount) // 80块钱
          let res2 = this.bigNumMultip(res1, this.slv, 4);
          let res3 = this.bigNumDivision(res2, twoSlv)
          let res4 = this.bigNumLessen(taxAmount, res3) // 最后100- 结果
          let amount = this.bigNumFixed(res4);
          let index = 1;
          this.searchFormData.cekcList.forEach(item => {
            item.xh = index++;
          })
          let ce = {
            ...this.searchFormData,
            cekcList:JSON.stringify(this.searchFormData.cekcList),
          }

          this.$emit('added', {newAmount: amount, kce: minusAmount, jshj: taxAmount, ceData: ce})
          this.closeSearch()
        }
      })

    },
    closeSearch() {
      this.showDialog = false;
      this.$refs.searchForm.resetFields();
      this.$refs.searchForm.clearValidate();
    },
    show(row, ceData) {
      this.reset()
      let slv = row.slv
      this.slv = slv
      this.searchFormData = cloneDeep(ceData)
      if (this.searchFormData.cekcList.length === 0) {
        this.addRow()
      }

      this.countTotal();
    },
    handChangePzlx() {
              try {
          if(item.pzlx==='01' || item.pzlx === '05'|| item.pzlx === '06'|| item.pzlx === '07'|| item.pzlx === '09'){
          this.searchFormData.cekcList.splice(i, 1,{
            ...this.searchFormData.cekcList[i],
            fpdm:''
          })
        }
      } catch (error) {
        
      }
      try {
        this.$refs.searchForm.clearValhandBckcjeidate();

      } catch (error) {
        
      }
    },
    addRow() {
      this.$nextTick(() => {
        this.searchFormData.cekcList.push({
          localId: new Date().getTime() +  Math.floor(Math.random() * 10000000),
          pzlx: '',
          fpdm: '',
          fphm: '',
          cepzhm: '',
          kjrq: '',
          pzhjje: '',
          bckcje: '',
          bz: '',
        })
      })
    },
    removeRow(index) {
      if (this.searchFormData.cekcList.length === 1) {
        this.$message.warning('至少保留一条数据')
        return
      }
      this.searchFormData.cekcList.splice(index, 1)
      this.countTotal();
    },
    jeBlur(row,type) {
      row[type] = valitedLimitNumber(this.bigNumFixed(row[type]), {leftLength: 16, rightLength: 2,})
      if (type === 'bckcje') {
        this.$nextTick(()=>{
          this.countTotal();
        })
      }

    },
    countTotal() {
      let temp = '0';
      this.searchFormData.cekcList.forEach(item => {
        if (item.bckcje) {
          temp = this.bigNumAdd(temp, item.bckcje);
        }
      });
      this.searchFormData.minusAmount = this.bigNumFixed(temp);
    },
    checkPzhjje() {
      let temp = '0';
      this.searchFormData.cekcList.forEach(item => {
        if (item.pzhjje) {
          let r1 = valitedLimitNumber(this.bigNumFixed(item.pzhjje), {leftLength: 16, rightLength: 2,})
          temp = this.bigNumAdd(r1, temp).toFixed(2)
        }
      });
      if (temp) {
        try {
          if (this.bigNumcomparedTo(temp, this.searchFormData.taxAmount)) {
            this.$message.warning('凭证合计金额不能大于含税金额')

          }
        } catch (error) {

        }
      }
    },
    handTaxAmount() {
      if (!this.searchFormData.taxAmount) return
      this.searchFormData.taxAmount = valitedLimitNumber(this.bigNumFixed(this.searchFormData.taxAmount), {
        leftLength: 16,
        rightLength: 2,
      })
    },
  },
}
</script>
<style lang="scss">
.button {
  margin-top: 20px;
  width: 100%;
  text-align: right;
}

.op-area {
  position: absolute;
  left: 0;
  top: 0;
}

.expand-wrapper {
  padding: 20px;
}

.form-con {
  width: 700px;
  margin: 0 auto;
}

.vxe-form--item-title {
  max-width: 500px;
}

.radio-area {
  width: 210px;
  margin: 0 auto;
  position: relative;
  left: 10px;
  padding-bottom: 5px;
}

.radio-tit {
  margin-right: 10px;
}

.box-tit {
  margin-bottom: 10px;
}

.my-search.vxe-input {
  height: 34px;
  width: 300px;
}

.box-body {
  margin-bottom: 10px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input[type="number"] {
  -moz-appearance: textfield;
}

input {
  border: none
}
</style>